package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServicelmpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    @Transactional //这个是事务注解，保证全成功或者全失败
    public void saveWithFlavor(DishDTO dto) {
        //先向菜品表插入数据，再向口味表插入数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.insert(dish);
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageFind(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.pageFind(dto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public String delete(List<Long> ids) {
        List<Long> collect = ids.stream().
                filter(id -> {
                    Dish dish = dishMapper.selectById(id);
                    return dish != null && dish.getStatus().equals(StatusConstant.DISABLE);
                })
                .filter(id -> {
                    Long setmeal = setmealDishMapper.getSetmealDishIdsByDishIds(id);
                    return setmeal == null;
                })
//                filter(id -> dishMapper.selectById(id).getStatus().equals(StatusConstant.ENABLE))
//                .filter(id->setmealDishMapper.getSetmealDishIdsByDishIds(id)!=0)
                .collect(Collectors.toList());
        String msg = "已经被删除的菜品有:";
        for (Long c : collect) {
            msg += dishMapper.selectById(c).getName() + " ";
        }
        if (msg.equals("已经被删除的菜品有:")) {
            throw new DeletionNotAllowedException("您所选中的所有菜品都在起售或被套餐所关联，请更改后重试！");
        }

        System.out.println(msg);
        //删除菜品表中的菜品数据,
        dishMapper.deleteBatchIds(collect);
        //删除菜品关联的口味数据
        //collect.forEach(id->dishFlavorMapper.deleteByDishId(id));
        dishFlavorMapper.deleteByDishIds(collect);
        return msg;
    }

    @Override
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.updateById(dish);
        //修改菜品的口味信息涉及增删改，为了方便，我们先把所有口味都删除再新增上要求的口味信息
        Long id = dish.getId();
        dishFlavorMapper.deleteByDishId(id);
        List<DishFlavor> flavors = dto.getFlavors();
        flavors.forEach(flavor -> {
            flavor.setDishId(id);
            dishFlavorMapper.insert(flavor);
        });
    }

    @Override
    public DishVO findById(Long id) {
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);//这里copy完属性还有flavor没有查到

        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(queryWrapper);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);
    }


    @Override
    public List<DishVO> findBycategoryId(Long categoryId) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        List<Dish> dishes = dishMapper.selectList(queryWrapper);
        return dishes.stream()
                .map(dish -> {
                    QueryWrapper<DishFlavor> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("dish_id", dish.getId());
                    List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(queryWrapper1);
                    DishVO vo = new DishVO();
                    BeanUtils.copyProperties(dish, vo);
                    vo.setFlavors(dishFlavors);
                    return vo;
                })
                .filter(v->v.getStatus().equals(StatusConstant.ENABLE))
                .collect(Collectors.toList());
    }
}
